package com.myapp.servlet;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.myapp.sqlmapper.SQLUtil;
import com.myapp.util.CommUtil;
import com.myapp.util.Consts;
import com.myapp.util.DBUtil;
import com.myapp.util.JsonUtil;
import com.myapp.util.MD5;

public class UserLogin extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 4124250479327869574L;

	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();

		String nickName = request.getParameter("nickName");
		String password = request.getParameter("password");
		if (CommUtil.isBlank(password) || CommUtil.isBlank(nickName)) {
			String result = CommUtil.setResultInfo(jsonMap, Consts.CHECK_CODE, Consts.ARG_DESCRIBE);
			CommUtil.responseJson(result, response);
			System.out.println("/userLogin 昵称或密码为空 ");
			return;
		}
		List<String> paramList = new ArrayList<String>();
		paramList.add(nickName);
		paramList.add(MD5.md5(password));
		String sql = SQLUtil.getSql("userMapper.userLogin", paramList);
		try {
			ResultSet rs = DBUtil.exeQuery(sql);
			Map<String, String> retMap = new HashMap<String, String>();
			// 有结果集
			while (rs.next()) {
				retMap.put("id", rs.getString("id"));
				retMap.put("machineID", CommUtil.isNull(rs.getString("machine_id")));
				retMap.put("companyID", CommUtil.isNull(rs.getString("company_id")));
				retMap.put("createDT", rs.getString("createdt"));
				retMap.put("lastLoginDT", CommUtil.isNull(rs.getString("lastlogindt")));
				retMap.put("speakFlag", rs.getString("speakFlag"));
				retMap.put("rescode", Consts.SUCCESS_CODE);
				retMap.put("resmsg", Consts.SUCCESS_DESCRIBE);
				String result = JsonUtil.getJsonStringFromMap(retMap);
				CommUtil.responseJson(result, response);
				return;
			}
			// 无结果集
			String result = CommUtil.setResultInfo(jsonMap, Consts.CHECK_CODE, "nickName.or.password.error");
			CommUtil.responseJson(result, response);
			System.out.println("/userLogin 用户名或密码不正确");
			return;
		} catch (Exception e) {
			e.printStackTrace();
			String result = CommUtil.setResultInfo(jsonMap, Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001);
			CommUtil.responseJson(result, response);
		} finally {
			DBUtil.closeConn();
		}

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		this.doGet(request, response);
	}
}
